<!--
 * @Author: 宋绍华
 * @Date: 2024-11-12 14:58:02
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-13 10:25:00
 * @FilePath: \sr_system_manager_ui\src\views\project\components\MyProject\Cooperative.vue
 * @Description: 项目成员
-->
<template>
  <div :class="[props.mode === 'add' ? 'px-20px' : '']">
    <div class="mb-24px flex justify-end">
      <el-button  :class="[props.mode === 'add' ? 'mt-10px' : 'mt-[-32px]']"  v-if="props.mode !== 'view'" type="primary" @click="addMember">新增</el-button>
    </div>
    <el-table border :data="tableData" style="width: 100%">
      <el-table-column label="序号" width="48">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="unitName" label="单位名称">
        <template #default="scope">
          <el-input v-if="mode !== 'view'" :maxlength="50" style="width: 136px" v-model="scope.row.unitName"
            placeholder="请输入" />
          <span v-else>{{ scope.row.unitName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="managerName" label="项目联系人">
        <template #default="scope">
          <el-input :maxlength="50" v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.managerName"
            placeholder="请输入" />
          <span v-else>{{ scope.row.managerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="managerPhone" label="联系电话">
        <template #default="scope">
          <el-input :maxlength="11" v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.managerPhone"
            placeholder="请输入" />
          <span v-else>{{ scope.row.managerPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="collaboration" label="外拨经费">
        <template #default="scope">
          <el-input-number :controls='false' :min="0" :maxlength="14" v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.collaboration"
            placeholder="请输入" />
          <span v-else>{{ scope.row.collaboration }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="props.mode !== 'view'">
        <template #default="scope">
          <el-button type="danger" link @click="deleteMember(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  mode: {
    type: String as PropType<'add' | 'edit' | 'view'>,
    default: 'add'
  }
})
import { CooperativeCreateApi, getCoopDetailsApi } from '@/api/project';
import { BaseSuccessRespDTO, ProjectCooperativeUnitsVO } from '@/api/project/types';

const tempData = {
  /**
   * 合同金额(万元)
   */
  collaboration: undefined,
  /**
   * 单位名称
   */
  unitName: undefined,
  managerPhone: undefined,
}
const tableData = ref([])
const route = useRoute()

// 添加成员
const addMember = () => {
  tableData.value.push({ ...tempData })
}

// 获取详情
const { runAsync: getCoopDetails } = useRequest(getCoopDetailsApi, {
  manual: true,
  onSuccess: (res: ProjectCooperativeUnitsVO[]) => {
    tableData.value = res || []
  }
})

watch(
  () => [props.mode, props.projectId],
  val => {
    if (props.mode !== 'add' || props.projectId) {
      getCoopDetails({ projectId: props.projectId || route.query.projectId })
    }
  },
  {
    immediate: true
  }
)

// 删除成员
const deleteMember = (index: number) => {
  tableData.value.splice(index, 1)
}

const validate = () => {
  return tableData.value.every(i => {
    const isEmpty = Object.keys(i).every(key => {
      if (key === 'managerPhone' && !/^1\d{10}$/.test(i[key])) {
        return false
      }
      if (i[key] === undefined) {
        return false
      }
      return true
    })


    return isEmpty
  })
}

// 创建or更新
const { runAsync: coCreate } = useRequest(CooperativeCreateApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO, params) => {
    console.log(res, 'res');
    if (res.isSuccess && (params[0].isSave || params[0].isTemp)) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
    }

    return res.isSuccess
  }
})

// 创建项目
const create = async (isTemp: boolean = false, isSave: boolean = false) => {
  // 暂存
  if (isTemp) {
    coCreate({ unitsDetailDTOList: tableData.value, isTemp, projectId: props.projectId })
    return true
  }

  // 数据为空，可以直接放过去
  if (tableData.value.length === 0) return true
  const res = await validate()
  console.log(res, 'res');

  if (!res) {
    ElMessage.error('请完善正确内容')
    return false
  } else {
    let data = tableData.value?.map(i => {
      return {
        i: i.id,
        unitName: i.unitName,
        managerName: i.managerName,
        managerPhone: i.managerPhone,
        collaboration: i.collaboration
      }
    })
    try {
      const res = await coCreate({ isSave, unitsDetailDTOList: data, projectId: props.projectId, isTemp: props.mode !== 'add' ? false : isTemp })
      // if (props.mode !== 'add') {
      //   console.log(res, 'res');
      //   return res
      // } else {
      //   const res = await coCreate({ unitsDetailDTOList: tableData.value, isTemp, projectId: props.projectId })
      //   console.log(res, 'res');
      //   return res
      // }
      return res
    } catch (error) {
      console.log(error, 'error');
    }
  }
}

defineExpose({
  create
})
</script>


<style scoped lang="scss">
.title {
  --at-apply: flex items-center mr-48px;
}


:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>